// 引入SDK核心类
const QQMapWX = require('../libs/qqmap-wx-jssdk.js');
// 实例化API核心类
const qqmapsdk = new QQMapWX({
  key: 'GKJBZ-GBB34-2MQU6-FA5DS-VWJWT-RLF7D' // 必填 申请的开发者密钥
});
const zhuan_dingwei = require('../utils/dingwei.js');
const app = getApp();

// 引入插件：微信同声传译
const plugin = requirePlugin('WechatSI');
// 获取全局唯一的语音识别管理器recordRecoManager
const manager = plugin.getRecordRecognitionManager();
const API_KEY = 'lKuvxeNclUEmiVo5OU3gGAvj';
const SECRET_KEY = 'rg14Z4kS7LKsJ04PSYoYzF4FGpnDGA32';

Page({
  data: {
    recordState: false,
    content: '',
    src: '',
    messages: '',
    accessToken: '',
    address: '', // 输出
    latitude: 31.86, // 经纬度先预设一个，获取地址信息后再替换
    longitude: 117.27,
  },

  // 获取当前位置信息
  getUserLocation() {
    const that = this;
    wx.getSetting({
      success: (res) => {
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                });
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      });
                      // 再次授权，调用wx.getLocation的API
                      wx.getLocation({
                        type: 'wgs84',
                        success(res) {
                          console.log(res);
                          that.setData({
                            latitude: res.latitude,
                            longitude: res.longitude
                          });
                          that.njx();
                        }
                      });
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      });
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          // 调用wx.getLocation的API
          wx.getLocation({
            type: 'wgs84',
            success(res) {
              console.log("undefined", res);
              that.setData({
                latitude: res.latitude,
                longitude: res.longitude
              });
              that.njx();
            }
          });
        } else {
          // 调用wx.getLocation的API
          wx.getLocation({
            type: 'wgs84',
            success(res) {
              console.log(res);
              that.setData({
                latitude: res.latitude,
                longitude: res.longitude
              });
              that.njx();
            }
          });
        }
      }
    })
  },

  njx() {
    const that = this;
    console.log(this.data.latitude);
    wx.request({
      url: 'https://apis.map.qq.com/ws/geocoder/v1/',
      data: {
        location: `${this.data.latitude},${this.data.longitude}`,
        key: 'GKJBZ-GBB34-2MQU6-FA5DS-VWJWT-RLF7D',
        get_poi: 0,
        output: 'json'
      },
      success(res) {
        that.setData({
          address: res.data.result.address
        });
        console.log(res);
      },
      fail(error) {
        console.error('逆地理编码失败：', error);
      }
    });
  },

  // 逆地址解析
  reverseGeocoder(id) {
    const that = this;
    let location = "";
    const s = `markers[${parseInt(id)}]`;
    let stationInfo = {};
    that.data.markers.forEach((item) => {
      if (item.id == id) {
        location = `${item.latitude},${item.longitude}`;
        stationInfo = item;
        return false;
      }
    });
    console.log(location);
    qqmapsdk.reverseGeocoder({
      location: location || '', // 获取表单传入的位置坐标,不填默认当前位置,示例为string格式
      success: function (res) { // 成功后的回调
        console.log(res);
        stationInfo.title = res.result.formatted_addresses.recommend; // res.result.address
        stationInfo.callout.content = res.result.formatted_addresses.recommend;
        that.setData({
          [s]: stationInfo
        });
        that.openLocation(stationInfo);
      },
      fail: function (error) {
        console.error(error);
      }
    });
  },

  // 查看位置
  openLocation(stationInfo) {
    // 使用微信内置地图查看位置接口
    wx.openLocation({
      latitude: stationInfo.latitude, // 纬度，浮点数，范围为90 ~ -90
      longitude: stationInfo.longitude, // 经度，浮点数，范围为180 ~ -180。
      name: stationInfo.title, // 要找的地方名字(某某饭店)
      address: stationInfo.title, // 地址：要去的地点详细描述
      scale: 14, // 地图缩放级别,整形值,范围从1~28。默认为最大
      infoUrl: '' // 在查看位置界面底部显示的超链接,可点击跳转(测试好像不可用)
    });
  },

  initRecord() {
    const that = this;
    manager.onStart = function (res) {
      that.setData({
        recordState: true
      });
      console.log("成功开始录音识别", res);
    }
    manager.onError = function (res) {
      console.error("error msg", res);
    }
    manager.onStop = function (res) {
      that.setData({
        recordState: false
      });
      console.log('..............结束录音');
      console.log('录音临时文件地址 -->' + res.tempFilePath);
      console.log('录音总时长 -->' + res.duration + 'ms');
      console.log('文件大小 --> ' + res.fileSize + 'B');
        console.log('语音内容 --> ' + res.result);
        that.sendMessage(res.result);
        if (res.result == '') {
          wx.showModal({
            title: '提示',
            content: '听不清楚,请重新说一遍!',
            showCancel: false
          })
          return;
        }
        var text = that.data.content + res.result;
        that.setData({
          content: text
        })
      }
    },
    getToken() {
      const url_token = `https://aip.baidubce.com/oauth/2.0/token?client_id=${API_KEY}&client_secret=${SECRET_KEY}&grant_type=client_credentials`;
  
      wx.request({
        url: url_token,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        success: res => {
          console.log(res);
          const accessToken = res.data.access_token;
          this.setData({ accessToken });
        },
        fail: err => {
          console.error('获取access_token失败', err);
        }
      });
    },
    sendMessage(c) {
      const content = c;
      const messages = this.data.messages;
      const accessToken = this.data.accessToken;
  
      const userMessage = {
        role: 'user',
        content: '现在请你扮演一个旅行伴侣和助手，为游客提供30字以内的建议和指引，回答下面的问题：' + content,
      };
      console.log(userMessage);
      
      this.getBotResponse(content, accessToken);
      this.setData({
        content: '',
      }); 
      console.log(messages);
    },
  
    getBotResponse(userInput, accessToken) {
      const url_chat = `https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=${accessToken}`;
  
      const payload = {
        "messages": [
          {
            "role": "user",
            "content": '现在请你扮演一个旅行伴侣和助手，为游客提供30字以内的建议和指引，回答下面的问题：'+userInput
          }
        ]
      };
  
      wx.request({
        url: url_chat,
        method: 'POST',
        data: payload,
        header: {
          'Content-Type': 'application/json'
        },
        success: res => {
          console.log(res);
          const botMessage = {
            role: 'bot',
            content: res.data.result,
          };
          this.wordYun(res.data.result);
          this.setData({
            messages: res.data.result,
          });
        },
        fail: err => {
          console.error('获取机器人响应失败', err);
        }
      });
    },
    wordYun(c){
      var that = this;
      var content = c;
      plugin.textToSpeech({
        lang: "zh_CN",
        tts: true,
        content: content,
        success: function (res) {
          console.log("succ tts", res.filename);
          that.setData({
            src: res.filename
          })
          that.yuyinPlay();
        },
        fail: function (res) {
          console.log("fail tts", res)
        }
      })
    },
  
    yuyinPlay: function (e) {
      if (this.data.src == '') {
        console.log('暂无语音');
        return;
      }
      this.innerAudioContext = wx.createInnerAudioContext();
      this.innerAudioContext.src = this.data.src;
      this.innerAudioContext.play();
    },
  
    end: function (e) {
      if (this.innerAudioContext) {
        this.innerAudioContext.pause();
      }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      this.initRecord();
      this.getToken();
      //this.getUserLocation();
      //this.getUserLocationTimer = setInterval(this.getUserLocation, 600000); // 每分钟更新一次位置
        //this.getUserLocation();//用户授权获取地理信息，可以写在onShow里进行判断是否授权获取地理信息
        /*this.data.markers.forEach((item, i) => {
            //高德地图、腾讯地图以及谷歌中国区地图使用的是GCJ-02坐标系
            let gcj02tobd09 = zhuan_dingwei.wgs84togcj02(item.longitude, item.latitude);
            //console.log(i, gcj02tobd09);
            item.longitude = gcj02tobd09[0];
            item.latitude = gcj02tobd09[1];
        });*/
        //console.log(this.data.markers);
    },
 
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function (e) {
      //创建内部 audio 上下文 InnerAudioContext 对象。
      this.innerAudioContext = wx.createInnerAudioContext();
      this.innerAudioContext.onError(function (res) {
        console.log(res);
        wx.showToast({
          title: '语音播放失败',
          icon: 'none',
        })
      }) 
    },
    touchStart: function (e) {
      manager.start({
        lang: 'zh_CN',
      })
    },
    touchEnd: function (e) {
      manager.stop();
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
 
    },
    
  
})


